import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TodoList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new TodoListState();
}

class TodoListState extends State<TodoList> {
  final _biggerFont = TextStyle(fontSize: 14.0);
  //存放待办清单
  List<String> _todoItems = [];
  //存放已完成清单
  List<String> _todoItemsFinished = [];
  //作为参数传给listview，表示如何展示清单信息
  final _isFinished = true;

  //当记录是0的时候，在屏幕中显示提示语
  Widget _hintText(String text) {
    return new Text(
      text,
      style: new TextStyle(
        fontSize: 20.0,
        color: Colors.grey,
      ),
    );
  }

  //存储string数组的key
  final String _todoListName = 'todosName';
  final String _todoListFinishedName = 'todosFinishedName';
  //保存待办事项数组方法
  saveTodos(list) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(_todoListName, list);
    print('============调用saveTodos保存数据后的待办清单');
    print(list);
  }

  //保存已完成事项方法
//  saveTodosFinished(list) async {
//    SharedPreferences prefs = await SharedPreferences.getInstance();
//    prefs.setStringList(_todoListFinishedName, list);
//  }

  //获取待办事项存储的对应数据
  Future<List<String>> getTodos() async {
    List<String> a;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    a = prefs.getStringList(_todoListName);
    return a;
  }

  void d() {
    Future<List<String>> a = getTodos();
    a.then(
      (List<String> a) {
        setState(() {
          _todoItems = a;
        });
      },
    );
  }

  //获取已办事项存储的对应数据
//  Future<List<String>> getTodosFinished() async {
//    //var _todoItemsFinished;
//    SharedPreferences prefs = await SharedPreferences.getInstance();
//    _todoItemsFinished = prefs.getStringList(_todoListFinishedName);
//    return _todoItemsFinished;
//  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          '待办事项',
          style: _biggerFont,
        ),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.list),
            onPressed: _allTodoItems,
          ),
        ],
      ),
      body: new Center(
        child: _todoItems.length == 0
            ? _hintText('点击按钮新增一条事项')
            : TodoListView(_todoItems, !_isFinished),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () => _todoEdit(),
        tooltip: '新增待办事项',
        child: new Icon(
          Icons.add,
          size: 25.0,
        ),
      ),
    );
  }

//  Widget b() {
//    return () {
//      Future<List<String>> a = getTodos();
//      a.then(
//        (List<String> a) {
//          print('===========调用getTodos后');
//          print(a);
//          return TodoListView(a, !_isFinished);
//        },
//      );
//    };
//  }

  //ListView控件，用于滚动展示待办事项信息
  Widget TodoListView(items, isFinished) {
    print('===================ListView里的待办事项: $items');
    return new ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        print(index);
        if (index < items.length) {
          print(items.length);
          return TodoItem(items, index, isFinished);
        }
      },
    );
  }

  //ListTile控件，描绘每个待办事项
  Widget TodoItem(items, i, isFinished) {
    print('===================ListTile里的');
    print(items);
    if (isFinished) {
      return new Container(
        child: new ListTile(
          title: new Text(
            items[items.length - i - 1],
            style: new TextStyle(
                decoration: TextDecoration.lineThrough,
                color: Colors.grey,
                decorationColor: Colors.teal),
          ),
          onTap: () {},
        ),
        decoration: new BoxDecoration(
          border: new Border(
            bottom: new BorderSide(
              color: Colors.grey[300],
              width: 0.5,
            ),
          ),
        ),
      );
    } else {
      return new Container(
        child: new ListTile(
          title: new Text(
            items[i],
          ),
          onTap: () {
            _showDialog(i);
          },
        ),
        decoration: new BoxDecoration(
          border: new Border(
            bottom: new BorderSide(
              color: Colors.grey[300],
              width: 0.5,
            ),
          ),
        ),
      );
    }
  }

  //弹出对话框询问是否标记成完成，并提供两个按钮选择
  void _showDialog(int i) {
    showDialog(
      context: context,
      builder: (context) {
        return new AlertDialog(
          title: new Text('"${_todoItems[i]}"    是否标记成已完成'),
          actions: <Widget>[
            new FlatButton(
              onPressed: () => Navigator.pop(context),
              child: new Text(
                '否',
                style: new TextStyle(
                  fontSize: 18.0,
                ),
              ),
            ),
            new FlatButton(
              onPressed: () {
                _removeTodoItem(i);
                Navigator.pop(context);
              },
              child: new Text(
                '是',
                style: new TextStyle(
                  fontSize: 18.0,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  //从列表中删除该事项，并告知程序状态发生变化，需要重绘视图UI
  _removeTodoItem(int index) {
    setState(
      () {
        _todoItemsFinished.add(_todoItems[index]);
        _todoItems.removeAt(index);
        //saveTodosFinished(_todoItemsFinished);
      },
    );
  }

  //点击右下角的按钮后，将新的路由页面推入栈中，该页面包含一个文本编辑控件，用于用户编辑内容。
  void _todoEdit() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (BuildContext context) {
          return new Scaffold(
            appBar: new AppBar(
              title: new Text(
                '添加待办事项',
                style: _biggerFont,
              ),
              leading: new BackButton(),
            ),
            body: new TextField(
              autofocus: true,
              decoration: new InputDecoration(
                hintText: '编辑待办事项',
                contentPadding: const EdgeInsets.all(10.0),
              ),
              onSubmitted: (text) {
                if (text.length == 0) {
                  Navigator.of(context).pop();
                } else {
                  _todoItemsChanged(text);
                  Navigator.of(context).pop();
                }
              },
            ),
          );
        },
      ),
    );
  }

  //这是导航到所有事项的方法，该方法包含导航到新页面的路由以及包含的内容
  void _allTodoItems() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return new Scaffold(
              appBar: new AppBar(
                title: new Text(
                  '完成清单',
                  style: _biggerFont,
                ),
              ),
              body: new Center(
                child: _todoItemsFinished.length == 0
                    ? _hintText('你还没完成任何待办事项')
                    : TodoListView(_todoItemsFinished, _isFinished),
              ));
        },
      ),
    );
  }

  //待办事项列表有新的变化，通过setState重绘页面UI
  _todoItemsChanged(String text) {
    setState(
      () {
        _todoItems.add(text);
        saveTodos(_todoItems);
      },
    );
  }
}
